package com.hundsun.cprs.yyt.service.rabbit.listener;

import java.text.MessageFormat;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.account.enums.EnumQuotaTransType;
import com.hundsun.cprs.yyt.service.account.service.IntegralService;
import com.hundsun.cprs.yyt.service.common.dto.FundBatchRequest;
import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.enums.EnumFundBidCode;
import com.hundsun.cprs.yyt.service.common.service.RemoteTradeFundService;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.order.domain.OrderItem;
import com.hundsun.cprs.yyt.service.order.dto.OrderInfo;
import com.hundsun.cprs.yyt.service.order.enums.EnumDeliveryMethod;
import com.hundsun.cprs.yyt.service.order.enums.EnumOrderSNCode;
import com.hundsun.cprs.yyt.service.order.enums.EnumsOrderStatus;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.service.quota.service.QuotaHoldService;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustBSType;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;

/**
 * 订单创建通用后置处理器
 * @author linrl
 * @date 2019年3月3日
 */
@Component
public class OrderPostProcessListener implements MessageListener {
    
    private static Log logger = LogFactory.getLog(OrderPostProcessListener.class);
    @Autowired
    private TradeEntrustService tradeEntrustService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private IntegralService integralService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RemoteTradeFundService remoteTradeFundService;
    @Autowired
    private QuotaHoldService quotaHoldService;

    @Override
    public void onMessage(Message message) {
        String receviedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
        try {
            if (RoutingKeyConstants.YYT_ORDER_PAID.equals(receviedRoutingKey)) {
                OrderInfo orderInfo = JSON.parseObject(new String(message.getBody(),message.getMessageProperties().getContentEncoding()), OrderInfo.class);
                if (logger.isDebugEnabled()) {
                    logger.debug("订单支付通知:" + JSON.toJSONString(orderInfo));
                }
                if (StringUtils.equals(orderInfo.getAreaCode(), EnumAreaCode.RETAIL_AREA.getCode())) {
                    //零售区订单处理
                    handleOrderFromRelailArea(orderInfo);
                } else if(StringUtils.equals(orderInfo.getAreaCode(), EnumAreaCode.WHOLESALE_AREA.getCode())){
                    //批发区订单处理
                    handleOrderFromWholesaleArea(orderInfo);
                } else {
                    logger.error(MessageFormat.format("订单[{0}]来源区域[{1}]系统无法处理", orderInfo.getSn(),orderInfo.getAreaCode()));
                }
            }
        } catch (Exception e) {
            logger.error("订单创建监听器业务处理异常",e);
        }
    }
    
    /**
     * 零售区订单业务后置处理
     * @param order
     */
    protected void handleOrderFromRelailArea(OrderInfo order){
        //赠送积分
        //createIntegralLog(order);
        //赠送配额
        addQuota(order);
        //自动待发货
        deliveryOrder(order);
        //生成委买单,匹配实际商家(委卖单)商品
        entrustBuy(order);
        //更新订单详情
        orderService.updateOrder(order);
    }
    
    /**
     * 批发区订单后置处理
     * @param order
     */
    protected void handleOrderFromWholesaleArea(OrderInfo order) {
        // 后置处理
        if (EnumDeliveryMethod.ENTRUST.ordinal() == order.getDeliveryType()) {
            // 挂售业务流程
            entrustSell(order);
        } else {
            // 自动待发货
            deliveryOrder(order);
        }
        // 更新订单详情
        orderService.updateOrder(order);

        try {
            receiptOrder(order);
        } catch (Exception e) {
            logger.error(order.getSn() + "商家收款处理异常:",e);
        }
    }
    
    
    /**
     * 批发区商家收款
     */
    protected void receiptOrder(OrderInfo order){
        //批发区給卖家转款
        if (order.isWholesaleArea()) {
            UserAccountDTO sellerInfo = remoteUserService.getUserDetailByUserId(order.getSellerId());
            if (sellerInfo == null) {
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1001.getErrorNo(),"卖家信息状态异常");
            }
            
            FundBatchRequest request = FundBatchRequest.builder("system", EnumOrderSNCode.getOrderFundSN(order.getSn(), EnumOrderSNCode.FUND_IN), 
                   MessageFormat.format("[{0}({1})]订单卖家收款", order.isWholesaleArea()?EnumAreaCode.WHOLESALE_AREA.getDesc():EnumAreaCode.RETAIL_AREA.getDesc(),order.getOrderItems().get(0).getGoodsName()));
            request.addTask(sellerInfo.getFundAccount(), EnumFundBidCode.CFUND_170101, order.getSn(), order.getPrice());
            remoteTradeFundService.batchExecute(request);
        }
    }
    
    /**
     * 赠送积分
     */
    protected void createIntegralLog(OrderInfo order){
    	if (order.getIntegralRewardAmount() > 0 ) {
    		integralService.addIntegeral(order.getUserId(), order.getIntegralRewardAmount().intValue(), order.getSn(), "商品[" + order.getOrderItems().get(0).getGoodsName()+"]赠送积分");
		}
    }
    
    /**
     * 赠送配额
     */
    protected void addQuota(OrderInfo order){
    	if (order.getOrderItems().get(0).getQuotaRewardAmount() > 0) {
    		quotaHoldService.addQuota(order.getUserId(), 
					  order.getOrderItems().get(0).getRewardQuotaId(), 
					  order.getOrderItems().get(0).getQuotaRewardAmount(), 
					  EnumQuotaTransType.TRANS_0201.getCode(), "零售区下单赠送配额");
		}
        //accountService.addQuota(order.getUserId(), order.getQuotaRewardAmount(),"零售区下单赠送配额");
    }
    
    protected void deliveryOrder(OrderInfo order){
        //更新订单状态
        order.setStatus(EnumsOrderStatus.WAIT_DELIVERY.getStatus());
    }
    
    /**
     * 生成挂买单
     * @param order
     */
    protected void entrustBuy(OrderInfo order){
        for(OrderItem item : order.getOrderItems()){
            TradeEntrust entrust = new TradeEntrust();
            entrust.setOrderSn(order.getSn());
            entrust.setUserId(order.getUserId());
            entrust.setUserName(order.getUserName());
            entrust.setFundAccount(order.getFundAccount());
            entrust.setEntrustAmount(Long.valueOf(item.getQuantity()));
            entrust.setEntrustPrice(item.getPrice()); // 以当前商品单价委买,用于后续匹配完成后，计算卖家利润
            entrust.setEntrustBs(EnumEntustBSType.BUY.getCode().toString());
            entrust.setGoodsId(item.getGoodsId());
            entrust.setGoodsCode(item.getGoodsCode());
            tradeEntrustService.createAndCommitEntrust(entrust);
        }
    }
    
    /**
     * 生成挂售单
     * @param order
     */
    protected void entrustSell(OrderInfo order){
        for(OrderItem item : order.getOrderItems()){
            TradeEntrust entrust = new TradeEntrust();
            entrust.setOrderSn(order.getSn());
            entrust.setUserId(order.getUserId());
            entrust.setUserName(order.getUserName());
            entrust.setFundAccount(order.getFundAccount());
            entrust.setEntrustAmount(Long.valueOf(item.getQuantity()));
            entrust.setEntrustPrice(item.getPrice()); // 以当前商品折扣单价委售,用于后续匹配完成后，计算卖家利润
            entrust.setEntrustBs(EnumEntustBSType.SELL.getCode().toString());
            entrust.setGoodsId(item.getGoodsId());
            entrust.setGoodsCode(item.getGoodsCode());
            tradeEntrustService.createAndCommitEntrust(entrust);
        }
        order.setStatus(EnumsOrderStatus.ENTRUST.getStatus());
    }
}
